﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;
using RED_NET_Core.Entity;
using RED_NET_Core.Helper;

/// <summary>
///Login 的摘要说明
/// </summary>

namespace RED_NET_Core.DAL
{
    public class Login_DAL
    {
      
        public Login_DAL()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        #region [判断是否是合法登录用户]

        /// <summary>
        /// 判断是否是合法登录用户，若是则放回该用户id，否则返回-1
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public int IsValidUser(string UserName, string pass)
        {
            SqlHelper Shp = new SqlHelper();
            String SmdStr = "select * from _Users where _UserName='" + UserName + "'";
            SqlCommand Smd = Shp.GetCommand(SmdStr, null);
            SqlDataReader Sdr = Smd.ExecuteReader();
            Smd.Dispose();
            if (Sdr.Read())
            {
                String password = Sdr["_Password"].ToString();
                if (password == pass)
                {
                    return (int)Sdr["_UId"];
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                return -1;
            }

        }

        #endregion

        #region [获取登录后用户的信息]

        /// <summary>
        /// 搜索对应用户ID的用户并返回用户的详细资料，不存在则返回null
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public Users GetMessageOfUser(int uid)
        {
            SqlHelper Shp = new SqlHelper();
            String SmdStr = "select * from _Users where _UId='" + uid.ToString() + "'";
            SqlCommand Smd = Shp.GetCommand(SmdStr, null);
            SqlDataReader Sdr = Smd.ExecuteReader();
            
            if (Sdr.Read())
            {
                Users user = new Users();
                user.UserId = uid;
                user.UserName = Sdr["_UserName"].ToString();
                user.Password = Sdr["_Password"].ToString();
                user.Right = Int32.Parse(Sdr["_Right"].ToString());
                user.NickName = Sdr["_NickName"].ToString();
                user.College = Int32.Parse(Sdr["_College"].ToString());
                user.Major = Int32.Parse(Sdr["_Major"].ToString());
                user.Class = Int32.Parse(Sdr["_Class"].ToString());
                user.LastLoginTime = Convert.ToDateTime(Sdr["_LaseLoginTime"].ToString());
                user.Myattention = Int32.Parse(Sdr["_Myattention"].ToString());
                user.AttentionBy = Int32.Parse(Sdr["_AttentionBy"].ToString());
                user.BlogNum = Int32.Parse(Sdr["_BlogNum"].ToString());
                user.AvatarUrl = Sdr["_AvatarUrl"].ToString();
                return user;
            }
            else
                return null;
            Shp.Close();
        }

        #endregion

        #region[修改最后登录时间]

        /// <summary>
        /// 修改最后登录时间
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool UpdateLoginTimeOfUser(int uid)
        {
            SqlHelper Shp = new SqlHelper();
            DateTime timeNow = new DateTime();
            timeNow = DateTime.Now;
            string cmd = "UPDATE _Users SET(_LaseLoginTime) VALUES('" + timeNow + "')";
            SqlCommand sqlCmd = Shp.GetCommand(cmd, null);
            SqlDataReader sqlReader = sqlCmd.ExecuteReader();
            sqlCmd.Dispose();
            if (sqlReader.Read())
            {
                return true;
            }
            else return false;
        }

        #endregion

        #region [发表新博文后修改拥有的博文数]

        /// <summary>
        /// 发表新博文后修改拥有的博文数
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="blogNum"></param>
        /// <returns></returns>
        public bool UpdateBlogNumOfUser(int uid, int blogNum)
        {
            SqlHelper Shp = new SqlHelper();
            blogNum += 1;
            string cmd = "UPDATE _Users SET(_LaseLoginTime) VALUES('" + blogNum + "')";
            SqlCommand sqlCmd = Shp.GetCommand(cmd, null);
            SqlDataReader sqlReader = sqlCmd.ExecuteReader();
            if (sqlReader.Read())
            {
                return true;
            }
            else return false;
        }

        #endregion

        #region [修改密码]

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="userName"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public bool UpdatePasswordOfUser(int uid, string userName, string oldPassword, string newPassword)
        {
            SqlHelper Shp = new SqlHelper();
            String SmdStr = "select * from _Users where _UId='" + uid.ToString() + "'";
            SqlCommand Smd = Shp.GetCommand(SmdStr, null);
            SqlDataReader Sdr = Smd.ExecuteReader();
            if (Sdr.Read())
            {
                Users user = new Users();
                user.UserId = uid;
                user.UserName = Sdr["_UserName"].ToString();
                user.Password = Sdr["_Password"].ToString();
                if (user.UserName == userName && user.Password == oldPassword)
                {
                    SmdStr = "UPDATE _Users SET(_LaseLoginTime) VALUES('" + user.BlogNum.ToString()+ "')";
                    Smd = Shp.GetCommand(SmdStr, null);
                    Sdr = Smd.ExecuteReader();
                    if (Sdr.Read())
                    {
                        return true;
                    }
                    else return false;
                }
                return false;
            }
            return false;
        }

        #endregion

        #region [修改昵称]

        /// <summary>
        /// 修改昵称
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="newNickName"></param>
        /// <returns></returns>
        public bool UpdateNickNameOfUser(int uid, string newNickName)
        {
            SqlHelper Shp = new SqlHelper();
            string cmd = "UPDATE _Users SET(_NickName) VALUES('" + newNickName + "')";
            SqlCommand sqlCmd = Shp.GetCommand(cmd, null);
            SqlDataReader sqlReader = sqlCmd.ExecuteReader();
            if (sqlReader.Read())
            {
                return true;
            }
            else return false;
        }

        #endregion

        #region [获取关注者信息]

        /// <summary>
        /// 获取关注者的信息（UId和UserName）
        /// </summary>
        /// <param name="nUId">用户Id</param>
        /// <param name="nNum" ></param>
        /// <returns>返回含有UId,UserName,_AvatarUrl的DataTable</returns>
        public DataTable GetMyAttentionInfo(int nUId, int nNum)
        {

            string _smdStr = "select  * from _UserRel where _UId='" + nUId.ToString() + "'";
            if (nNum != 0)
            {
                _smdStr = "select top "+nNum.ToString()+"  * from _UserRel where _UId='" + nUId.ToString() + "'";
            }
            OwnSqlHelper _shp = new OwnSqlHelper();
            DataTable _sdt = _shp.ExecuteQuery(_smdStr, System.Data.CommandType.Text);
            DataTable _dt = new DataTable();
            DataColumn _dc;

            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType("System.Int32");
            _dc.ColumnName = "_Id";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _dt.Columns.Add(_dc);

            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType("System.Int32");
            _dc.ColumnName = "_UId";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _dt.Columns.Add(_dc);
            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType("System.String");
            _dc.ColumnName = "_NickName";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _dt.Columns.Add(_dc);

            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType("System.String");
            _dc.ColumnName = "_AvatarUrl";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _dt.Columns.Add(_dc);

            int i;
            for (i = 0; i < _sdt.Rows.Count; i++)
            {
                DataRow _dr = _dt.NewRow();

                Users _users = this.GetMessageOfUser((int)_sdt.Rows[i]["_AttentionId"]);
                _dr["_UId"] = _users.UserId;
                _dr["_NickName"] = _users.NickName;
                _dr["_AvatarUrl"] = "~" + _users.AvatarUrl.Substring(2);
                _dr["_Id"] = _sdt.Rows[i]["_Id"];
                _dt.Rows.Add(_dr);
            }
            return _dt;
        }
        #endregion

        #region[添加关注]
        /// <summary>
        /// 添加关注
        /// </summary>
        /// <param name="nUId"></param>
        /// <param name="nAttentionTd"></param>
        /// <returns></returns>
        public int AddAttention(int nUId, int nAttentionTd)
        {
            UsersRel _userRel = new UsersRel();
            _userRel.UId = nUId;
            _userRel.AttentionId = nAttentionTd;
            _userRel.AddTime = System.DateTime.Now;
            return _userRel.AddItem();

        }
        #endregion

        #region[删除关注信息]
        /// <summary>
        /// 
        /// </summary>
        /// <param name="nId"></param>
        public void DeleteUserRel(int nId)
        {
            OwnSqlHelper _shp = new OwnSqlHelper();
            string _smdStr = "delete from _UserRel where _Id='" + nId.ToString() + "'";
            _shp.ExecuteNonQuery(_smdStr, System.Data.CommandType.Text);
        }

        #endregion

        #region[获取院级用户]
        /// <summary>
        /// 获取院级用户
        /// </summary>
        /// <returns>返回UId和NickName</returns>
        public DataTable GetCollegeUser()
        {
            string SmdStr = "select _UId,_NickName,_College from _Users where _Right=1";
            OwnSqlHelper _shp = new OwnSqlHelper();
            return _shp.ExecuteQuery(SmdStr, System.Data.CommandType.Text);
        }
        #endregion

        #region[获取班级用户]
        /// <summary>
        /// 获取班级用户
        /// </summary>
        /// <returns>返回UId和NickName</returns>
        public DataTable GetClassUser(int nCollegeId)
        {
            string SmdStr = "select _UId,_NickName from _Users where _Right= 0 and _College = " + nCollegeId.ToString();
            OwnSqlHelper _shp = new OwnSqlHelper();
            return _shp.ExecuteQuery(SmdStr, System.Data.CommandType.Text);
        }
        #endregion

        #region[判断是否存在关注关系]
        /// <summary>
        /// 判断是否存在关注关系
        /// </summary>
        /// <param name="nUId1"></param>
        /// <param name="nUId2">被关注的用户</param>
        /// <returns>若nUId1关注了nUId2则返回1，否则返回0</returns>
        public int JudgeUserRel(int nUId1, int nUId2)
        {
            string SmdStr = "select _Id from _UserRel where _UId='" + nUId1.ToString() + "' and _AttentionId ='"+nUId2.ToString()+"'";
            OwnSqlHelper _shp = new OwnSqlHelper();
            DataTable _dt = _shp.ExecuteQuery(SmdStr, System.Data.CommandType.Text);
            if (_dt.Rows.Count > 0)
            {
                return 1;
            }
            else
                return 0;
        }
        #endregion

        #region[添加访问记录]
        /// <summary>
        /// 添加访问记录
        /// </summary>
        /// <param name="nId"></param>
        /// <param name="nVisitId"></param>
        public void AddVisitInfo(int nId, int nVisitId)
        {
            string SmdStr = "select _VisitId1 ,_VisitId2 ,_VisitId3,_VisitId4,_VisitId5,_VisitTime1,_VisitTime2,_VisitTime3,_VisitTime4,_VisitTime5,_Top from _Users where _UId='" + nVisitId.ToString() + "'";
            OwnSqlHelper _shp = new OwnSqlHelper();
            DataTable _dt = _shp.ExecuteQuery(SmdStr, System.Data.CommandType.Text);
            int[] _visitId = new int[5]; 
            int _top = Int32.Parse(_dt.Rows[0]["_Top"].ToString()); 
            DateTime[] _dateTime = new DateTime[5];
            if (_top > 0)
            {
                _visitId[0] = (int)_dt.Rows[0]["_VisitId1"];
                _dateTime[0] = (DateTime)_dt.Rows[0]["_VisitTime1"];
            }
            if (_top>1)
            {
            _visitId[1] = (int)_dt.Rows[0]["_VisitId2"];
            _dateTime[1] = (DateTime)_dt.Rows[0]["_VisitTime2"];
            }
            if (_top > 2)
            {
            _visitId[2] = (int)_dt.Rows[0]["_VisitId3"];
            _dateTime[2] = (DateTime)_dt.Rows[0]["_VisitTime3"];
            }
            if (_top > 3)
            {
            _visitId[3] = (int)_dt.Rows[0]["_VisitId4"];
            _dateTime[3] = (DateTime)_dt.Rows[0]["_VisitTime4"];
            }
            if (_top > 4)
            {
                _visitId[4] = (int)_dt.Rows[0]["_VisitId5"];
                _dateTime[4] = (DateTime)_dt.Rows[0]["_VisitTime5"];

            }
          
           
            
           
            int i;
            for (i = 0; i < _top; i++)
            {
                if (_visitId[i] == nId)
                {
                    while (i < _top-1)
                    {
                        _visitId[i] = _visitId[i + 1];
                        _dateTime[i] = _dateTime[i + 1];
                        i++;
                    }
                    _top--;
                    break;
                }
            }
            if (_top == 5)
            {
                for (i = 0; i < 4; i++)
                {
                    _visitId[i] = _visitId[i + 1];
                    _dateTime[i] = _dateTime[i + 1];
                }
                _visitId[4] = nId;
                _dateTime[4] = System.DateTime.Now;
            }
            else
            {
                _visitId[_top] = nId;
                _dateTime[_top] = System.DateTime.Now;
                _top++;
         }
            for (i = _top; i < 5; i++)
            {
                _dateTime[i] = System.DateTime.Now;
                _visitId[i] = 0;
            }
            SqlParameter[] _param = new SqlParameter[12];
            _param[0] = new SqlParameter("@VisitId1", _visitId[0].ToString());
            _param[1] = new SqlParameter("@VisitId2", _visitId[1].ToString());
            _param[2] = new SqlParameter("@VisitId3", _visitId[2].ToString());
            _param[3] = new SqlParameter("@VisitId4", _visitId[3].ToString());
            _param[4] = new SqlParameter("@VisitId5", _visitId[4].ToString());
            _param[5] = new SqlParameter("@VisitTime1", _dateTime[0].ToString());
            _param[6] = new SqlParameter("@VisitTime2", _dateTime[1].ToString());
            _param[7] = new SqlParameter("@VisitTime3", _dateTime[2].ToString());
            _param[8] = new SqlParameter("@VisitTime4", _dateTime[3].ToString());
            _param[9] = new SqlParameter("@VisitTime5", _dateTime[4].ToString());
            _param[10] = new SqlParameter("@Top", _top.ToString());
            _param[11] = new SqlParameter("@UId", nVisitId.ToString());
            string SmdStr2 = "UPDATE _Users SET _VisitId1=@VisitId1 , _VisitId2=@VisitId2 , _VisitId3=@VisitId3 , _VisitId4=@VisitId4 , _VisitId5=@VisitId5 , _VisitTime1=@VisitTime1 , _VisitTime2=@VisitTime2 , _VisitTime3=@VisitTime3 , _VisitTime4=@VisitTime4 , _VisitTime5=@VisitTime5 , _Top=@Top  where _UId = @UId";
             _shp.ExecuteNonQuery(SmdStr2, _param, System.Data.CommandType.Text);
            
         


        }
        #endregion

        #region[获得最近访客信息]
        /// <summary>
        /// 获得最近访客信息
        /// </summary>
        /// <param name="nUId"></param>
        /// <returns></returns>
        public DataTable GetLatestVisitor(int nUId)
        {
            string SmdStr = "select _VisitId1 ,_VisitId2 ,_VisitId3,_VisitId4,_VisitId5,_VisitTime1,_VisitTime2,_VisitTime3,_VisitTime4,_VisitTime5,_Top from _Users where _UId='" + nUId.ToString() + "'";
            OwnSqlHelper _shp = new OwnSqlHelper();
            DataTable _dt = _shp.ExecuteQuery(SmdStr, System.Data.CommandType.Text);
            DataTable _ans = new DataTable();
            DataColumn _dc;
            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType("System.Int32");
            _dc.ColumnName = "_VisitId";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _ans.Columns.Add(_dc);
            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType("System.String");
            _dc.ColumnName = "_NickName";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _ans.Columns.Add(_dc);
            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType("System.String");
            _dc.ColumnName = "_AvatarUrl";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _ans.Columns.Add(_dc);

            _dc = new DataColumn();
            _dc.DataType = System.Type.GetType(" System.DateTime");
            _dc.ColumnName = "_VisitTime";
            _dc.ReadOnly = false;
            _dc.Unique = false;
            _ans.Columns.Add(_dc);

            int i;
            int _top=(int)_dt.Rows[0]["_Top"];
            for (i = 1; i <= _top; i++)
            {
                DataRow _dr = _ans.NewRow();
                _dr["_VisitId"] = (int)_dt.Rows[0]["_VisitId" + (_top - i + 1).ToString()];
                _dr["_VisitTime"]=(DateTime)_dt.Rows[0]["_VisitTime"+(_top-i+1).ToString()];
                Users _user = GetMessageOfUser((int)_dr["_VisitId"]);
                _dr["_NickName"] = _user.NickName;
                _dr["_AvatarUrl"] = _user.AvatarUrl;
                _ans.Rows.Add(_dr);
            }
            return _ans;

        }
        #endregion

        #region[获取对应用户的权限值]
        public int GetRight(int Uid)
        {
            OwnSqlHelper _shp = new OwnSqlHelper();
            String cmdText = "select _Right from _Users where _UId = '" + Uid.ToString() + "'";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@UId",Uid)
            };
            DataTable _dt = null;
            int right = -1 ;
            try
            {
                _dt = _shp.ExecuteQuery(cmdText, System.Data.CommandType.Text);
                right = Int32.Parse(_dt.Rows[0]["_Right"].ToString());
            }
            catch (Exception ex)
            {
                right = -1;
                throw ex;
            }
            return right;
        }
        #endregion

        #region[获取对应用户的学院id]
        public int GetcollegeId(int Uid)
        {
            SqlHelper helper = new SqlHelper();
            String cmdText = "select _College from _Users where _UId = @UId";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@UId",Uid)
            };
            SqlCommand cmd = helper.GetCommand(cmdText, param);
            SqlDataReader dr;
            int collegeId;
            try
            {
                dr = cmd.ExecuteReader();
                collegeId = Int32.Parse(dr["_College"].ToString());
            }
            catch (Exception ex)
            {
                collegeId = -1;
                throw ex;
            }
            return collegeId;
        }
        #endregion
        #region[获取对应用户的密码]
        /// <summary>
        /// 获取对应用户的密码
        /// </summary>
        /// <param name="uid">用户id</param>
        /// <returns></returns>
        public string GetPass(int uid)
        {
            OwnSqlHelper _shp = new OwnSqlHelper();
            string _smdStr = "select _Password from _Users where _UId='" + uid.ToString() + "'";
            try
            {
                return _shp.ExecuteScalar(_smdStr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


    }
}
